let bx = 1240 / device.width
let by = 2772 / device.height

//是否打开控制台
let isOpenConsole = false
//是否开启调试模式
let debugMode = false
//日志的最大行数
let maxLine = 7
//设置控制台
function init(params) {
    //获取悬浮窗权限
    auto.waitFor()
    //打开录屏权限
    getScreenCapture()
    //设置屏幕宽高
    setScreenMetrics(1240, 2772)
    if (params && params.isOpenConsole) {
        isOpenConsole = params.isOpenConsole
        setConsole()
    }
    if (params && params.debugMode) {
        debugMode = params.debugMode
    }
}

//进入抖音首页
function enterDouYinIndex() {
    app.startActivity({
        data: "snssdk1128://feed",
    });
}

var win;
//设置控制台
function setConsole() {
    win = floaty.rawWindow(
        <vertical h="200" bg="#000000" w="500" alpha="0.4">
            <text id="log" line="5" textColor="white" textSize="14sp" typeface="normal"></text>
        </vertical>
    );
    //悬浮穿透
    win.setTouchable(false);
    //悬浮移动
    win.setPosition(device.width - 500, 500)
}

//输出日志到控制台
function log(data, type) {
    console.log(data)
    if (!type) {     //默认是info
        type = "info"
    }
    if (isOpenConsole) {
        //是否输出到界面
        let isShow = false
        if (debugMode && type === "debug") {
            isShow = true
        } else if (type === "info") {
            isShow = true
        }
        if (isShow) {
            threads.start(() => {
                ui.run(() => {
                    try {
                        let t = win.log.text()
                        let size = t.split("\n")
                        let v = ""
                        if (size.length > maxLine) {
                            for (let i = size.length - maxLine + 1; i < size.length - 1; i++) {
                                v += size[i] + "\n"
                            }
                        } else {
                            v = t
                        }
                        v += data + "\n"
                        // console.log(win.log)
                        win.log.setText(v);
                    } catch (e) {
                        console.log("输出日志异常:" + e)
                    }
                });
            })
        }
    }
}

function _press(x, y, time) {
    if (!time) {
        time = 100
    }
    press(x * bx, y * by, time)
}

//以图找图
function findImage(template, options) {
    let p = null;
    try {
        let base = captureScreen();
        template = images.read(`./image/${template}`);
        if (template == null) {
            tool.log("模板不存在")
        } else {
            p = images.findImage(base, template, options)
        }
    }
    catch (e) {
        tool.log(`找图异常:${e}`);
    }
    return p;
}

//重启app
function restartApp(t) {
    killApp(t)
    sleep(1000)
    openApp(t)
}

//打开app
function openApp(appName) {
    tool.log("打开应用：" + appName)
    launchApp(appName);
    sleep(2000)
    if (text("允许").exists()) {
        click("允许")
    }
    sleep(2000)
    if (text("打开").exists()) {
        click("打开")
    }
    sleep(1000)
    if (textContains("跳过").exists()) {
        clickText("跳过")
    }
}

//关闭app
// function killApp (appName) {
//     tool.log("关闭应用：" + appName)
//     launchApp(appName);
//     sleep(5000)
//     home();
//     sleep(1000)
//     recents()
//     sleep(1500)
//     swipe(device.width / 2 + 150, device.height / 2 - 200, device.width / 2 + 150, 50, 200)
//     sleep(1000)
//     home();
// }

//关闭app
function killApp(appName) {
    let forcedStopStr1 = ["停止", "结束运行", "确定", "结束", "停", "强行停止"]
    let forcedStopStr2 = ["确定", "结束", "停", "强行停止", "结束运行"];
    let packageName = app.getPackageName(appName);//获取应用包名 通过软件名
    if (packageName) {
        app.openAppSetting(packageName);//进入应用设置信息
        sleep(2000);
        for (let i = 0; i < forcedStopStr1.length; i++) {
            if (text(forcedStopStr1[i]).exists()) {
                let forcedStop = text(forcedStopStr1[i]).find();
                let x = forcedStop[0].bounds().centerX() * bx
                let y = forcedStop[0].bounds().centerY() * by
                click(x, y);
                sleep(1000);
                sleep(1000);
            } else {
                // console.log(`未找到${forcedStopStr1[i]}`)
            }
        }
        for (let i = 0; i < forcedStopStr2.length; i++) {
            if (text(forcedStopStr2[i]).exists()) {
                let forcedStop = text(forcedStopStr2[i]).find();
                let x = forcedStop[forcedStop.length - 1].bounds().centerX() * bx
                let y = forcedStop[forcedStop.length - 1].bounds().centerY() * by
                click(x, y);
                sleep(1000);
                break
            } else {
                // console.log(`未找到${forcedStopStr2[i]}`)
            }
        }
        back();
    }
}

//等待ID出现并点击
function clickId(ids, time) {
    try {
        time = time || 5000
        idContains(ids).findOne(5000)
        if (idContains(ids).exists()) {
            let p = idContains(ids).findOne(1000)
            if (p != null) {
                p = p.bounds()
                press(p.centerX() + 10, p.centerY(), 100);
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//等待文本出现并点击
function clickText(t, time) {
    try {
        time = time || 5000
        text(t).findOne(time)
        if (text(t).exists()) {
            let p = text(t).findOne(1000)
            if (p != null) {
                p = p.bounds()
                click(parseInt(p.centerX() * bx), parseInt(p.centerY() * by));
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//等待文本出现并点击
function clickTextContains(t, time) {
    try {
        time = time || 5000
        textContains(t).findOne(time)
        if (textContains(t).exists()) {
            let p = textContains(t).findOne(1000)
            if (p != null) {
                p = p.bounds()
                press(p.centerX() * bx, p.centerY() * bx, 100);
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//点击类名
function clickClassName(t, time) {
    try {
        time = time || 5000
        classNameContains(t).findOne(time)
        if (classNameContains(t).exists()) {
            let p = classNameContains(t).findOne(1000)
            if (p != null) {
                p = p.bounds()
                press(p.centerX() * bx, p.centerY() * bx, 100);
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//等待描述出现并点击
function clickDesc(t, time) {
    try {
        time = time || 5000
        descContains(t).findOne(time)
        if (descContains(t).exists()) {
            let p = descContains(t).findOne(1000)
            if (p != null) {
                p = p.bounds()
                // tool.log(`点击${t},X:${p.centerX() * bx + 10},Y:${p.centerY() * by}`)
                press(p.centerX() * bx, p.centerY() * bx, 10);
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//获取悬浮窗和录屏权限
function getScreenCapture() {
    let Thread = threads.start(function () {
        if (!floaty.checkPermission()) {
            // 没有悬浮窗权限，提示用户并跳转请求
            toast("本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。");
            floaty.requestPermission();
            exit();
        } else {
            toastLog('已有悬浮窗权限');
            //由于系统间同意授权的文本不同，采用正则表达式
        }

        let Allow = textMatches(/(允许|立即开始|统一)/).findOne(10 * 1000);
        if (Allow) {
            Allow.click();
        }

    });
    if (!requestScreenCapture(false)) {
        tool.log("请求录屏权限失败");
        return false;
    } else {
        tool.log("已获得录屏权限");
        Thread.interrupt()
        return true;
    }

}


//系统提示音
function playRingtone(time, size) {
    var size = size || 6
    var time = time || 1000
    var musice = android.media.RingtoneManager.TYPE_NOTIFICATION
    var mp = new android.media.MediaPlayer(); device.setMusicVolume(size)
    mp.setDataSource(context, android.media.RingtoneManager.getDefaultUri(musice));
    mp.prepare();
    mp.start();
}

//检测关闭悬浮窗
function closeCoupon() {
    if (handleLotteryResult()) {
        return
    }
    //关闭关键字
    let closeKeywords = ["关闭", "我知道了"]
    for (let i = 0; i < closeKeywords.length; i++) {
        if (text(closeKeywords[i]).exists()) {
            click(closeKeywords[i])
            return true;
        }
    }
}

//判断是否中奖
function handleLotteryResult() {
    let lotteryResult = false;
    //判断是否中奖
    if (textContains("领取奖品").exists() || textContains("恭喜").exists()) {
        lotteryResult = true;
    } else {
        // tool.log("没有抽中福袋")
    }
    return lotteryResult;
}


//当前页面是否含有某个关键字
function hasText(t) {
    let p = false;
    try {
        if (t === undefined || t === null) {
            t = '视频'
            return p;
        }
        var img = captureScreen();
        let res = paddle.ocr(img);
        for (let i = 0; i < res.length; i++) {
            let text = res[i].text
            // tool.log(`文字:${text}-${t}:${text.includes(t)}`)
            if (text.includes(t)) {
                p = res[i]
                break;
            }
        }
        img.recycle()
    } catch (e) {
        console.log(e)
    }
    return p;
}


//判断界面是否有变化
function isChange() {
    let p = null;
    let option = {
        "region": [0, 0, device.width, device.height],
        "threshold": 0.8
    }
    p = findImage("dqpm.png", option)
    if (p) {
        return true;
    } else {
        return false;
    }
}

//将文字对象转换为数组
function convertTextToArray(g) {
    let t = []
    for (let i = 0; i < g.length; i++) {
        let s = g[i]
        if (s.children === null) {
            t.push(s)
        } else {
            t = t.concat(convertTextToArray(s.children))
        }
    }
    return t;
}

//识别当前屏幕的文字
function getText(t) {
    let p = null;
    try {
        if (t === undefined || t === null) {
            t = '视频'
        }
        // requestScreenCapture(false);
        var img = captureScreen();
        let startfishTime = new Date().getTime();
        let res = gmlkit.ocr(img, "zh");
        res = convertTextToArray(res.children)
        // let res = paddle.ocr(img);
        let endfishTime = new Date().getTime();
        console.log("识别时间1：" + (endfishTime - startfishTime) + "ms");
        for (let i = 0; i < res.length; i++) {
            let text = res[i].text
            // tool.log(`文字:${text}-${t}:${text===t}`)
            if (text === t) {
                //tool.log("找到文字：" + JSON.stringify(res[i]));
                p = res[i]
                break;
            }
        }
        // img.recycle()
    } catch (e) {
        console.log(e)
    }
    return p;
}

//当前页面是否含有某个关键字
function hasText(t) {
    let p = false;
    try {
        if (t === undefined || t === null) {
            t = '视频'
            return p;
        }
        //当前屏幕截图
        let img = captureScreen();
        let startfishTime = new Date().getTime();
        let res = gmlkit.ocr(img, "zh");
        res = convertTextToArray(res.children)
        //  let res = paddle.ocr(img);
        let endfishTime = new Date().getTime();
        for (let i = 0; i < res.length; i++) {
            let text = res[i].text
            // tool.log(`文字:${text}-${t}:${text.includes(t)}`)
            if (text.includes(t)) {
                p = res[i]
                break;
            }
        }
        // img.recycle()
    } catch (e) {
        console.log(e)
    }
    return p;
}


//获取当前屏幕的文字,不分行
function getTextByScreenCapture(t) {
    let p = false;
    try {
        if (t === undefined || t === null) {
            t = '视频'
            return p;
        }
        let img = captureScreen();
        let res = gmlkit.ocr(img, "zh");
        res = res.children
        for (let i = 0; i < res.length; i++) {
            let text = res[i].text
            if (text.includes(t)) {
                p = res[i]
                break;
            }
        }
        img.recycle()
    } catch (e) {
        console.log(e)
    }
    return p;
}


//点击当前屏幕内的指定文字
function clickTextByScreenCapture(t) {
    let s = hasText(t)
    if (!s) {
        s = hasText(t)
        if (!s) {
            s = hasText(t)
            if (!s) {
                return false;
            } else {
                _press(s['bounds']['left'], s['bounds']['top'], 200)
                return true;
            }
        } else {
            _press(s['bounds']['left'], s['bounds']['top'], 200)
            return true;
        }
    } else {
        _press(s['bounds']['left'], s['bounds']['top'], 200)
        return true;
    }
}

//点击当前屏幕内的指定文字
function clickisTextByScreenCapture(t) {
    let s = getText(t)
    if (!s) {
        s = getText(t)
        if (!s) {
            s = getText(t)
            if (!s) {
                return false;
            } else {
                _press(s['bounds']['left'], s['bounds']['top'], 200)
                return true;
            }
        } else {
            _press(s['bounds']['left'], s['bounds']['top'], 200)
            return true;
        }
    } else {
        _press(s['bounds']['left'], s['bounds']['top'], 200)
        return true;
    }
}


//等待屏幕出现文字
function waitText(t, s) {
    if (!t) {
        t = 1000 * 10
    }
    let p = false;
    let startTime = new Date().getTime();
    do {
        if (new Date().getTime() - startTime > s) {
            console.log(`查找文字:${t}超时退出`)
            break;
        }
        p = hasText(t)
        if (p) {
            console.log(`找到文字:${t}了,p:${p}`)
            break;
        } else {
            console.log(`正在找文字:${t}`)
        }
        sleep(100)
    } while (true)
    sleep(500)
    return p;
}

exports.clickisTextByScreenCapture = clickisTextByScreenCapture
exports.getTextByScreenCapture = getTextByScreenCapture;
exports.waitText = waitText;
exports.setConsole = setConsole;
exports.findImage = findImage;
exports.restartApp = restartApp;
exports.openApp = openApp;
exports.killApp = killApp;
exports.clickId = clickId;
exports.clickText = clickText;
exports.clickDesc = clickDesc;
exports.getScreenCapture = getScreenCapture;
exports.playRingtone = playRingtone;
exports.closeCoupon = closeCoupon;
exports.handleLotteryResult = handleLotteryResult;
exports.clickClassName = clickClassName;
exports.getText = getText;
exports.init = init;
exports.clickTextByScreenCapture = clickTextByScreenCapture;
exports.enterDouYinIndex = enterDouYinIndex;
exports.isChange = isChange;
exports.log = log;
exports.press = _press;
exports.hasText = hasText;
exports.bx = bx;
exports.by = by;
exports.hasText = hasText;